package com.example.learningspringboot.mybatis.controller;

import com.example.learningspringboot.mybatis.pojo.User;
import com.example.learningspringboot.mybatis.services.MybatisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Mybatis的实例代码
 * <a href="https://mybatis.org/mybatis-3/zh_CN/">Mybatis官网</a>
 */
@RestController
@RequestMapping("/mybatis")
@Slf4j
public class MybatisController {

    private final MybatisService mybatisService;

    @Autowired
    public MybatisController(MybatisService mybatisService) {
        this.mybatisService = mybatisService;
    }

    @PostMapping("/create")
    public String create(String name, String age, String address) {
        log.info("name:{}, age:{}, address:{}", name, age, address);
        User user = new User();
        user.setName(name);
        user.setAge(Integer.parseInt(age));
        user.setAddress(address);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        mybatisService.createUser(user);
        log.info("created: {}", user.getId());
        return "created: " + user;
    }

    @PostMapping("/findById")
    public String findById(int id) {
        log.info("id:{}", id);
        User user = mybatisService.findById(id);
        log.info("findById user: {}", user);
        return "find user: " + user;
    }

    @PostMapping("/findByNameAndCreateTime")
    public String findByNameAndCreateTime(int id) {
        User userTemp = mybatisService.findById(8);
        log.info("findByNameAndCreateTime user: {}", userTemp);
        LocalDateTime createTime = userTemp.getCreateTime();
        String name = userTemp.getName();
        User user = mybatisService.findByNameAndCreateTime(name, createTime);
        return "find user: " + user;
    }

    @PostMapping("/findByCreateTime")
    public String findByCreateTime(int id) {
        log.info("findByCreateTime user: {}", mybatisService.findById(id));
        LocalDateTime createTime = mybatisService.findById(id).getCreateTime();
        User user = mybatisService.findByCreateTime(createTime);
        return "find user: " + user;
    }

    @PostMapping("/findByIds")
    public String findByIds() {
        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(1);
        ids.add(3);
        ids.add(4);
        List<User> users = mybatisService.findByIds(ids);
        return "find user: " + users;
    }

    @PostMapping("/delete")
    public String delete(int id){
        return mybatisService.deleteUser(id) > 0 ? "deleted" : "not found";
    }

}
